<template>
	<view class="container" style="padding: 0;">
		<!-- 顶部自定义导航 -->
		<tn-navbar :placeholder="true" fixed bg-color="#FFFFFF00" text-color="#000"> {{ title }} </tn-navbar>

		<!-- 商品列表 -->
		<view v-if="cartsData !== null && cartsData.length > 0" style="padding: 5px;">
			<view v-for="(place, index) in placeData" :key="index"
				style="padding: 10px 20px;display: flex;flex-direction: column;background-color: #fff;border-radius: 5px;">
				<view style="display: flex;align-items: center;">
					<tn-icon :name="place.logo ?? 'twitter'" :size="48" color="#f0ad4e"></tn-icon>
					<text style="font-weight: bold;">{{ place.nicename }}</text>
					<tn-icon name="right" :size="24" style="padding-left: 10px;"></tn-icon>
				</view>
				<view v-for="(item, index) in cartsData" :key="index"
					style="padding: 10px 0; display: flex;flex-direction: column;">
					<view v-if="item.pid === place.id" style="display: flex;align-items: center; position: relative;">
						<view>
							<tn-checkbox v-model="item.is_check" size="lg" checked-shape="circle" @change="cartChange"
								style="padding: 5px;"></tn-checkbox>
						</view>
						<view style="width: 100px;height: 120px;padding: 5px;" @tap="navToDisplay(item.puid)">
							<image style="border-radius: 5px;" :src="sConf.pics + (item.product.cover ?? [])[0].url"
								mode="scaleToFill"></image>
						</view>
						<view
							style="flex: 1;height: 120px;padding: 5px;display: flex;flex-direction: column;justify-content: space-between;align-items: start;">
							<view style="font-weight: bold;">{{ item.product.name }}</view>
							<view style="color: #999;">{{ item.product.jingle.title }}</view>
							<view style="width: 100%;display: flex;justify-content: space-between;">
								<view style="display: flex;gap: 5px;">
									<tn-icon v-if="item.product.is_share === 1" name="fire" color="#ff9a44"></tn-icon>
									<tn-icon v-if="item.product.is_master === 1" name="lucky-money"
										color="#ff6b6b"></tn-icon>
									<tn-icon v-if="item.product.exp > 0" name="flower" color="#96c93d"></tn-icon>
									<tn-icon v-if="item.product.point > 0" name="funds" color="#01beff"></tn-icon>
									<tn-tag v-for="(tag, index) in item.product.tag" :key="index" type="info"
										shape="round" font-size="16" :bg-color="tag.bgcolor"
										:text-color="tag.color">{{ tag.name }}</tn-tag>
								</view>
								<view style="color: #999;">
									<text>库存:{{ item.product.cur_num }}</text>
								</view>
							</view>
							<view style="width: 100%;display: flex;justify-content: space-between;">
								<view style="display: flex;">
									<text style="font-weight: bold;color: #dd524d;">￥{{ (item.product.price.price /
										100).toFixed(2)}}</text>
									<text
										style="text-decoration: line-through;color: #999;padding-left: 10px;">￥{{ (item.product.price.money
											/ 100).toFixed(2)}}</text>
								</view>
								<tn-number-box v-model="item.buy" :min="1" :step="1" :max="item.product.cur_num"
									bg-color="#f1f1f1" input-disabled @change="numChange"></tn-number-box>
							</view>
						</view>
						<!-- 移除按钮 -->
						<tn-icon class="unsteady" style="padding: 5px;" name="delete" :size="48"
							@tap="beRemove(item.id)"></tn-icon>
					</view>
				</view>
			</view>
		</view>

		<tn-empty v-else mode="cart"></tn-empty>

		<view class="tn-tabbar-height" style="height: 100px;"></view>

		<!-- 底部导航栏 -->
		<view class="goods-carts" style="background-color: #fff;">
			<view style="display: flex;justify-content: space-around;align-items: center;padding: 20px 10px;">
				<tn-checkbox v-model="allAgent" :active-value="1" :inactive-value="0" size="lg"
					@change="allChange">全选</tn-checkbox>

				<view style="color: #dd524d;font-size: smaller;display: flex;align-items: end;">
					<text>合计 ￥</text>
					<view class="buy-price">{{ (allPrice / 100).toFixed(2) }} </view>
				</view>

				<tn-button click-modifiers="stop" width="140px" height="60px" font-size="20px" bg-color="#000"
					@click="confirmReqsn" text-color="#fff"> 立即结算</tn-button>
			</view>
		</view>
	</view>

	<!-- 模态窗口 -->
	<tn-popup v-model="purch" open-direction="bottom">
		<view class="tn-p-lg" style="background-color: #f1f1f1;padding: 10px;height: 50vh;">
			<!-- 标题 -->
			<view style="display: flex;justify-content: center;padding: 15px 0;">
				<view style="font-size: large;">确认订单</view>
			</view>
			<!-- 收货地址 -->
			<view
				style="padding: 20px 10px;border-radius: 10px;display: flex;justify-content:space-between;background-color: #fff;margin-top:10px;"
				:class="warn ? 'warn-address' : ''" @tap="addressChange">
				<view style="font-weight: bold;"> 地址 </view>
				<view v-if="curAddress">
					<view> {{ zipStr(curAddress?.name) }} {{ zipStr(curAddress?.phone) }}</view>
					<view>{{ curAddress?.sheng }} {{ curAddress?.shi }} {{ curAddress?.xian }}
						{{ curAddress?.zhen }}
					</view>
					<view> {{ curAddress?.address }}</view>
				</view>
				<view v-else>
					<text style="color: #aaa;">请选择收货地址</text>
				</view>
			</view>
			<!-- 备注 -->
			<view style="border-radius: 10px;background-color: #fff;margin-top:10px;">
				<view style="padding: 20px 10px;display: flex;justify-content: space-between;">
					<view style="font-weight: bold;"> 备注 </view>
					<view style="color: #aaa;" @click="showNodeBlock">{{ nodeData ?? '无备注' }} ></view>
				</view>
			</view>

			<!-- 支付板块 -->
			<view style="border-radius: 10px;background-color: #fff;margin-top:10px;">
				<tn-radio-group v-model="selectPay" style="width: 100%;">
					<view style="width: 100%;padding: 10px 10px;display: flex;flex-direction: column;">
						<view
							style="display: flex;justify-content: space-between;align-items: center;width: 100%;padding: 20px 0;">
							<view style="display: flex;align-items: center;gap: 5px;">
								<tn-icon name="payment-wechat" color="#48AC35" size="64"></tn-icon>
								<text>微信支付</text>
							</view>
							<view class="">
								<tn-radio label="wxpay"></tn-radio>
							</view>
						</view>
						<view
							style="display: flex;justify-content: space-between;align-items: center;width: 100%;padding: 10px 0;">
							<view style="display: flex;align-items: center;gap: 5px;">
								<tn-icon name="payment-alipay" color="#469AE4" size="64"></tn-icon>
								<text>支付宝</text>
							</view>
							<view class="">
								<tn-radio label="zhifubao" disabled></tn-radio>
							</view>
						</view>
					</view>
				</tn-radio-group>
			</view>

			<!-- 支付按钮 -->
			<view class="toSubmitReqsn"
				style="border-radius: 10px;margin-top:10px;padding: 10px;display: flex;justify-content: center;color: #fff;"
				@click="reqsnChange">
				<view class="">
					支付金额 ￥{{ (allPrice / 100).toFixed(2) }}
				</view>
			</view>

			<!-- 选择收货地址 -->
			<tn-action-sheet ref="actionSheetRef"></tn-action-sheet>
			<!-- 填写备注 -->
			<tn-popup v-model="showNode" open-direction="bottom">
				<view class="tn-p-lg" style="background-color: #fff;padding: 10px;">
					<view style="font-weight: bold;"> 备注 </view>
					<textarea :value="nodeData ?? ''" placeholder-style="color:#aaa" maxlength="255"
						@input="conformNode" placeholder="选填,建议先与商家协商一致"
						style="background-color: #f1f1f1;width: 100%;height: 20vh;padding: 10px;border-radius: 10px;margin-top: 10px;"></textarea>
					<view class="toSubmitReqsn"
						style="border-radius: 10px;margin-top:10px;padding: 10px;display: flex;justify-content: center;color: #fff;"
						@click="showNodeBlock">
						<view class=""> 提交 </view>
					</view>
				</view>
			</tn-popup>
		</view>
	</tn-popup>
</template>

<script>
import utils from '@/common/utils';
export default {
	name: "cart",
	data() {
		return {
			title: '悦君玺 • 重庆',
			sConf: getApp().globalData,
			angle: 0, // 按钮特效 
			cartsData: null,
			allAgent: false, //选中所有
			allPrice: 0, //总计
			ordPrice: 0, // 原始价格


			addressData: null,
			curAddress: null,
			warn: false,

			purch: false, // 结算界面
			showNode: false,
			nodeData: null,
			selectPay: 'wxpay',

			placeData: [], // 商户数据
			staffData: null, // 个人数据
		};
	},
	onLoad() {
		console.log('onLoad', 'cart');
		this.loadMyCartList()
		this.loadStaffAddress()
		this.loadUserinfoData(this.sConf.auth.id)
	},
	onShow() {
		console.log('onShow');
	},
	mounted() {
		console.log('mounted', 'cart');
	},
	methods: {
		zipStr(e) {
			return utils.zipStr(e)
		},
		showNodeBlock() {
			this.showNode = !this.showNode
		},
		conformNode(e) {
			this.nodeData = e.detail.value
		},
		/**
		 * 加载个人信息
		 */
		loadUserinfoData(e) {
			let host = this.sConf.host + '/weapps/userinfo/' + e + '/';
			let token = this.sConf.token || '';
			utils.authenticatorRead(host, token).then((res) => {
				console.log('加载个人信息', res);
				if (res.rescode === 200) {
					this.staffData = res.resmsg
				}
			})
		},
		/**
		 * 加载我的购物车
		 */
		loadMyCartList() {
			console.log('loadMyCartList');
			let host = this.sConf.host + '/weapps/cart/';
			let token = this.sConf.token || '';
			let data = {
				sid: this.sConf.auth.id,
				status: 1
			}
			utils.authenticatorList(host, token, data).then((res) => {
				console.log('加载我的购物车', res);
				if (res.rescode === 200) {
					this.cartsData = res.resmsg
					let tmpData = []
					let placeData = []
					res.resmsg.forEach(item => {
						console.log(item);
						if (!tmpData.includes(item.pid)) {
							tmpData.push(item.pid)
							placeData.push(item.place)
						}
					})
					this.placeData = placeData
				}
			});
		},
		/**
		 * 移除商品
		 */
		beRemove(e) {
			console.log('beRemove', e);
			let that = this;
			uni.showModal({
				title: '确认',
				content: '是否要移除该商品',
				success(res) {
					if (res.confirm) {
						console.log('确认');
						let host = that.sConf.host + '/weapps/cart/' + e + '/';
						let token = that.sConf.token || '';
						let data = {
							status: 0
						}
						utils.authenticatorPatch(host, token, data).then((res) => {
							console.log('请求成功', res);
							if (res.rescode === 200) {
								that.loadMyCartList();
								uni.showToast({
									icon: 'success',
									title: '成功'
								});
							}
						});
					}
				}
			});
		},
		/**
		 * 导航到产品详单页
		 */
		navToDisplay(e) {
			console.log('navToDisplay', e);
			// #ifdef MP-WEIXIN
			wx.vibrateShort();
			// #endif
			// 关闭当前页面
			uni.redirectTo({
				url: '/pages/puctplay/puctplay?puct=' + e,
			});
		},
		/**
		 * 编辑商品数量
		 * @param {Object} e
		 */
		numChange() {
			console.log('numChange');
			this.allTotal()
		},
		/**
		 * 单品选中状态
		 */
		cartChange() {
			console.log('cartChange');
			this.allTotal()
		},
		/**
		 * 全部选中状态
		 */
		allChange() {
			console.log('allChange', this.allAgent);
			this.cartsData.forEach(item => {
				item.is_check = this.allAgent === 1 ? true : false

			});
			this.allTotal()
		},
		/**
		 * 计算合计金额
		 */
		allTotal() {
			console.log('allTotal');
			let sum = 0
			let old = 0
			this.cartsData.forEach(item => {
				if (item.is_check) {
					sum += item.product.price.price * (item.buy ?? 1)
					old += item.product.price.money * (item.buy ?? 1)
				}
			});
			this.allPrice = sum
			this.ordPrice = old
		},
		/**
		 * 确认订单
		 */
		confirmReqsn() {
			console.log('confirmReqsn');
			if (!this.staffData.parent) {
				// #ifdef MP-WEIXIN
				wx.vibrateShort();
				// #endif
				uni.showToast({
					icon: 'error',
					title: '下单失败,请加入团购'
				})
				return
			}

			if (this.allPrice === 0) {
				uni.showToast({
					icon: 'error',
					title: '未找到有效商品'
				});
				return
			}

			this.purch = !this.purch
		},
		/**
		 * 提交订单
		 */
		reqsnChange() {
			console.log('doReqsn');
			uni.showToast({
				title: '停用'
			})
			return

			if (!this.curAddress) {
				// #ifdef MP-WEIXIN
				wx.vibrateShort();
				// #endif
				this.warn = true
				uni.showToast({
					icon: 'error',
					title: '请选择收货地址'
				})
				return
			}

			let host = this.sConf.host + '/weapps/newReqsn/';
			let token = this.sConf.token || '';
			let data = {
				sid: this.sConf.auth.id,
				ads: this.curAddress.id,
				fprice: this.ordPrice,
				aprice: this.allPrice,
				node: this.nodeData,
				products: this.makeProductList()
			}
			utils.authenticatorPost(host, token, data).then((res) => {
				console.log('提交订单1', res);
				if (res.rescode === 200) {
					return res.resmsg
				} else {
					throw '创建订单失败';
				}
			}).then((res) => {
				console.log('提交订单2', res);
				this.postJsapiOrder(res)
			})
		},
		/**
		 * 创建jsapi订单
		 */
		postJsapiOrder(e) {
			let host = this.sConf.host + '/weapps/postReqsn/';
			let token = this.sConf.token || '';
			let data = {
				reqsn: e.reqsn
			}
			utils.authenticatorPost(host, token, data).then((res) => {
				if (res.rescode === 200) {
					return res.resmsg
				} else {
					throw '创建jsapi失败';
				}
			}).then((res) => {
				console.log('创建jsapi', res);
				this.requestPayment(res)
			});
		},
		/**
		 * 创建商品列表
		 */
		makeProductList() {
			let tmpData = []
			this.cartsData.forEach(item => {
				if (item.is_check) {
					tmpData.push({
						cid: item.product.id,
						pid: item.place.id,
						fpe: item.product.price.money,
						ape: item.product.price.price,
						num: item.buy ?? 1
					})
				}
			});
			return tmpData
		},
		/**
		 * 加载用户收货地址
		 */
		loadStaffAddress() {
			let host = this.sConf.host + '/weapps/address/';
			let token = this.sConf.token || '';
			let data = {
				sid: this.sConf.auth.id
			}
			utils.authenticatorList(host, token, data).then((res) => {
				console.log('加载收货地址', res);
				if (res.rescode === 200) {
					this.addressData = res.resmsg
				}
			});
		},
		/**
		 * 转换地址对象
		 * @param {Object} e
		 */
		convolAddress(e) {
			this.curAddress = this.addressData.find(item => item.id === e)
		},
		/**
		 * 调出收货地址选项框
		 */
		addressChange() {
			console.log('addressChange');
			let tmpData = []
			this.addressData.forEach(item => {
				tmpData.push({
					value: item.id,
					text: this.zipStr(item.name) + ' ' + this.zipStr(item.phone),
					desc: item.address
				})
				console.log('转换数据.');
			})
			this.$refs.actionSheetRef.show({
				actions: tmpData,
				title: '请选择收货信息',
				cancel: () => {
					return true
				},
				select: (index, value) => {
					console.log('选项被点击', index, value)
					this.convolAddress(value)
					this.warn = false
					return true
				}
			})
		},
	}
}
</script>

<style lang="scss" scoped>
/* 底部导航栏 */
.goods-carts {
	/* #ifndef APP-NVUE */
	display: flex;
	/* #endif */
	flex-direction: column;
	position: fixed;
	left: 0;
	right: 0;
	bottom: 0;
}

/* 浮动移除按钮	*/
.unsteady {
	position: absolute;
	top: 0;
	right: 0;
}

.warn-address {
	border: 1px solid #dd524d;
}

.buy-price::first-letter {
	font-size: larger;
}

.toSubmitReqsn {
	background: linear-gradient(135deg, $uni-color-success, $uni-color-banner);
}
</style>